package com.hansming.bss.modules.sfc.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hansming.bss.common.service.CrudService;
import com.hansming.bss.modules.sfc.dao.CarDatePriceDao;
import com.hansming.bss.modules.sfc.dao.CarInfoDao;
import com.hansming.bss.modules.sfc.dao.CarServeDao;
import com.hansming.bss.modules.sfc.entity.CarDatePrice;
import com.hansming.bss.modules.sfc.entity.CarInfo;
import com.hansming.bss.modules.sfc.entity.CarServe;
import com.hansming.bss.modules.sfc.util.TimeUtil;

/**
 * 房车服务信息Service
 * @author Hansming
 * @version 2017-09-18
 */
@Service
@Transactional(readOnly = true)
public class CarServeService extends CrudService<CarServeDao,CarServe>{

	@Autowired
	private CarServeDao carServeDao;
	
	@Autowired
	private CarDatePriceDao carDatePriceDao;
	
	@Autowired
	private CarInfoDao carinfoDao;
	
	@Autowired
	private CarServeDao carserveDao;
	
	public List<CarServe> getByCarExtrId(String carextrid){
		return carServeDao.getByCarExtrId(carextrid);
	}
	
	public List<CarServe> getByCarId(String carid){
		return carServeDao.getByCarId(carid);
	}
	
	public List<CarServe>	getmandatoryServe(){
		return carServeDao.getmandatoryServe();
	}
	
	//得到里程限制
	public List<CarServe> getservebymileage(String carid){
		return carServeDao.getservebymileage(carid);
	};
		
	//得到油量限制
	public	List<CarServe> getServeByOilmanager(String carid){
		return carServeDao.getServeByOilmanager(carid);
	};
		
	//得到支付方式
	public List<CarServe> getServeByPayway(String carid){
		return carServeDao.getServeByPayway(carid);
	};
	
	public List<CarServe> querys(){
		return carServeDao.querys();
	};
	
	//得到司机代驾的价格 
	public CarServe getServeByDrive(){
		return carServeDao.getServeByDrive();
	}
	
	//得到里程限制
	public CarServe getmileage(){
		return carServeDao.getmileage();
	};
	
	//得到油量限制
	public	CarServe getOilmanager(){
		return carServeDao.getOilmanager();
	};
		
	//得到支付方式
	public CarServe getPayway(){
		return carServeDao.getPayway();
	};
	
	/*
	 * 得到条件选择下的价格
	 * @Param
	 * 		id  车辆标识id
	 * 		startDate 起始日期 yyyy-MM-dd
	 * 		endDate  还车日期 yyyy-MM-dd
	 * 		starttime  整型数字  0代表00：00，1代表0：30，2代表01：00以此类推，最大47代表23：00
	 * 		serveid  为“|”分隔的服务id字符串；
	 * @Result
	 * 		js输出JSON
	 */
	public void getCarPriceDetai(HttpServletRequest request, HttpServletResponse response,String startDate,String endDate,int starttime,int endtime,String id,String serveid) throws ParseException, IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject(); 
        JSONArray datas = new  JSONArray();		//返回到前台的具体的价格日期信息json
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		
		BigDecimal totleprice = new BigDecimal("0.00");		//准备计算总价格的基础
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		CarInfo carinfo = carinfoDao.get(id);
		Date fdate = dft.parse(startDate);
		Calendar todatecal = Calendar.getInstance();
		todatecal.setTime(dft.parse(endDate));
		todatecal.set(Calendar.DATE, todatecal.get(Calendar.DATE)-1);
		Date tdate = dft.parse(dft.format(todatecal.getTime()));
		//若超过中午12点，则按照翌日的价格计算，起始的结束日期加1以下只为日期加1
		if(starttime >24){											
			Calendar fromcal = Calendar.getInstance();
			fromcal.setTime(dft.parse(startDate));
			fromcal.set(Calendar.DATE, fromcal.get(Calendar.DATE) + 1);
			fdate = dft.parse(dft.format(fromcal.getTime()));
			Calendar tocal = Calendar.getInstance();
			tocal.setTime(dft.parse(endDate));
			tocal.set(Calendar.DATE, tocal.get(Calendar.DATE));
			tdate = dft.parse(dft.format(tocal.getTime()));
			}	
		int hour = 0;										//多出整天数的时间，超过四小时算作一天，若不超过，按照比例每半小时为该天价格的1/16，单位为半小时
		int resulthour =endtime - starttime; 					//根据取车的时间 starttime 为 取车时间的id,id为0 = 00:00,id为1 = 00:30以此为例（tohour 同理)
		if(endtime == 0){
			Calendar tocal = Calendar.getInstance();
			tocal.setTime(tdate);
			tocal.set(Calendar.DATE, tocal.get(Calendar.DATE)-1);
			tdate = dft.parse(dft.format(tocal.getTime()));
		}
		BigDecimal extrPrice = new BigDecimal("0.00");				//超出整天数的小时所产生的额外价格
		if(resulthour >= 0 ){
			//超过一天的时间
			if(resulthour >8){
				Calendar tocal = Calendar.getInstance();			//days = days +1;
				tocal.setTime(tdate);
				tocal.set(Calendar.DATE, tocal.get(Calendar.DATE) + 1);
				tdate = dft.parse(dft.format(tocal.getTime()));
			}else{
				hour = resulthour;			//此为小时数为超过整天数4小时内，按每半小时当天单价的1/16计价
				//超出时间的价格计算，得出当日的价格/16*超出的时间
				CarDatePrice cardateprice = new CarDatePrice();
				cardateprice.setCarInfo(carinfo);
				cardateprice.setDatetime(dft.format(tdate));
				extrPrice = carDatePriceDao.getByDate(cardateprice.getCarInfo().getId(),cardateprice.getDatetime()).getPrice().divide(new BigDecimal("16")).multiply(new BigDecimal(String.valueOf(hour)));
				extrPrice = extrPrice.setScale(2,BigDecimal.ROUND_UP);
			}
		}else{
			if(resulthour < -40){
				hour = 48 + resulthour;
				CarDatePrice cardateprice = new CarDatePrice();
				cardateprice.setCarInfo(carinfo);
				cardateprice.setDatetime(dft.format(tdate));
				extrPrice = carDatePriceDao.getByDate(cardateprice.getCarInfo().getId(),cardateprice.getDatetime()).getPrice().divide(new BigDecimal("16")).multiply(new BigDecimal(String.valueOf(hour)));
				extrPrice = extrPrice.setScale(2,BigDecimal.ROUND_UP);
				Calendar tocal = Calendar.getInstance();
				tocal.setTime(tdate);
				tocal.set(Calendar.DATE, tocal.get(Calendar.DATE)-1);
				tdate = dft.parse(dft.format(tocal.getTime()));
			}
		}
		//得到该计算日期的时间段的价格总价
		List<CarDatePrice>	carpirces = carDatePriceDao.getByDateFrom(dft.format(fdate),dft.format(tdate),carinfo);
		if(carpirces != null){
			for(CarDatePrice p:carpirces){
				totleprice = totleprice.add(p.getPrice());
			}
		}
		
		//加上额外的价格			
		totleprice = totleprice.add(extrPrice);

		int day = TimeUtil.Datecalc(startDate,endDate);
		String[] serves = serveid.split("\\|");
		BigDecimal price = new BigDecimal("0.00");//计算服务总价
		//首先计算总价的订单取消险价格，总价会影响订单取消险的价格
		JSONObject jo1 = new JSONObject();
		jo1.put("serve","车辆租金");
		jo1.put("price", totleprice);
		datas.put(jo1);
		for(int i=0;i<serves.length;i++){
			if("7".equals(serves[i])){		//订单取消服务
				price = totleprice.multiply(new BigDecimal("0.04"));
				price = price.setScale(2,BigDecimal.ROUND_UP);
				JSONObject jo2 = new JSONObject();
				jo2.put("serve", "订单损失险");
				jo2.put("price",price);
				datas.put(jo2);
				totleprice = totleprice.add(price);
			}
		}
		//之后其他服务可随意增加价格
		for(int i=0;i<serves.length;i++){
			if(serves[i] != null && serves[i] != ""){
				if("5".equals(serves[i])){				
					CarServe serve = carserveDao.get("5");				
					price = serve.getCaritemprice().multiply(new BigDecimal(String.valueOf(day)));
					price = price.setScale(2,BigDecimal.ROUND_UP);
					JSONObject jo2 = new JSONObject();
					jo2.put("serve", "代驾服务");
					jo2.put("price",price);
					datas.put(jo2);
					totleprice = totleprice.add(price);
				}else if("6".equals(serves[i])){		//不计免赔服务
					CarServe serve = carserveDao.get("6");				
					price = serve.getCaritemprice().multiply(new BigDecimal(String.valueOf(day+1)));
					price = price.setScale(2,BigDecimal.ROUND_UP);
					JSONObject jo2 = new JSONObject();
					jo2.put("serve", "不计免赔险");
					jo2.put("price",price);
					datas.put(jo2);
					totleprice = totleprice.add(price);
				}else if("8".equals(serves[i])){
					CarServe serve = carserveDao.get("8");				//承租人责任险
					price = serve.getCaritemprice().multiply(new BigDecimal(String.valueOf(day+1)));
					price = price.setScale(2,BigDecimal.ROUND_UP);
					totleprice = totleprice.add(price);
					JSONObject jo2 = new JSONObject();
					jo2.put("serve", "承租人责任险");
					jo2.put("price",price);
					datas.put(jo2);
				}
			}	
		}
		
		
		jsonObject.put("code", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
}
